class BurndownsController < ApplicationController
  # GET /burndowns
  # GET /burndowns.xml
  def index
    if current_user.account == nil
      redirect_to new_account_path
    else
      @burndowns = Burndown.find(:all)
  
      respond_to do |format|
        format.html # index.html.erb
        format.xml  { render :xml => @burndowns }
      end
    end
  end

  # GET /burndowns/1
  # GET /burndowns/1.xml
  def show
    @burndown = Burndown.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @burndown }
    end
  end

  # GET /burndowns/new
  # GET /burndowns/new.xml
  def new
    load_basecamp_projects
    @burndown = Burndown.new
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @burndown }
    end
  end

  # GET /burndowns/1/edit
  def edit
    @burndown = Burndown.find(params[:id])
    load_basecamp_projects(@burndown.project_id)
  end

  # POST /burndowns
  # POST /burndowns.xml
  def create
    @burndown = Burndown.new(params[:burndown])
    @burndown.account_id = current_user.account.id

    respond_to do |format|
      if @burndown.save
        flash[:notice] = 'Burndown was successfully created.'
        format.html { redirect_to(@burndown) }
        format.xml  { render :xml => @burndown, :status => :created, :location => @burndown }
      else
        format.html do 
          load_basecamp_projects(@burndown.project_id)
          render :action => "new"
        end
        format.xml  { render :xml => @burndown.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /burndowns/1
  # PUT /burndowns/1.xml
  def update
    @burndown = Burndown.find(params[:id])

    respond_to do |format|
      if @burndown.update_attributes(params[:burndown])
        flash[:notice] = 'Burndown was successfully updated.'
        format.html { redirect_to(@burndown) }
        format.xml  { head :ok }
      else
        format.html do 
          load_basecamp_projects(@burndown.project_id)
          render :action => "edit" 
        end
        format.xml  { render :xml => @burndown.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /burndowns/1
  # DELETE /burndowns/1.xml
  def destroy
    @burndown = Burndown.find(params[:id])
    @burndown.destroy

    respond_to do |format|
      format.html { redirect_to(burndowns_url) }
      format.xml  { head :ok }
    end
  end
  
  private
  def load_basecamp_projects(current_project = nil)
    basecamp = BasecampWrapper.create_wrapper
    basecamp.connect!(current_user.account)
    @projects = basecamp.projects.map { |p| [p.name, p.id] }
    
    if (current_project == nil) then
      current_project = @projects[0][1]
    end
    
    @milestones = basecamp.milestones(current_project).map { |m| [m.title, m.id] }
  end
end
